﻿using System.IO;
using System.Xml;
using System.Xml.Linq;

namespace DBFile.Core.Extensions
{
	public static class Extensions
	{
		public static void LoadFromDB(this XmlDocument document, string filename)
		{
            XmlReaderSettings settings = new XmlReaderSettings();
            settings.CloseInput = true;

            XmlReader reader = XmlReader.Create(DBFile.OpenText(filename), settings);
            
			document.Load(reader);
		}

        public static XDocument LoadFromDB(this XDocument document, string filename)
        {
            return XDocument.Load(DBFile.OpenText(filename));
        }

        public static XElement LoadFromDB(this XElement element, string filename)
        {
            return XElement.Load(DBFile.OpenText(filename));
        }

        public static void SaveToDB(this XDocument document, string filename)
        {
            StringWriter writer = new StringWriter();
            document.Save(writer);

            DBFile.Save(filename, writer.ToString(), "xml/text");
        }

        // This may not make any sense ...
        public static void SaveToDB(this XElement element, string filename)
        {
            StringWriter writer = new StringWriter();
            element.Save(writer);

            DBFile.Save(filename, writer.ToString(), "xml/text");
        }
	}
}
